<template>
  <div class="home">
    <header-selected
      v-show="selectedList.length"
      :baseUrl="baseUrl"
      :selectedList="selectedList"
      @remove="removeItem"
      @change="$emit('change', $event)"
    ></header-selected>
    <div class="list">
      <home-product
        v-for="(item, index) in list"
        :key="item.title"
        :item="item"
        :index="index"
        @add="add"
        @remove="remove"
        :selectedList="selectedList"
        :baseUrl="baseUrl"
        ref="products"
      ></home-product>
    </div>
  </div>
</template>

<script>
import headerSelected from './components/headerSelected.vue' // 头部选择的商品
import homeProduct from './components/homeProduct.vue' // 主页的商品
import axios from 'axios' // 引入axios

export default {
  // 注册组件
  components: {
    headerSelected,
    homeProduct
  },
  // 数据变量
  data () {
    return {
      list: [], // 数据
      selectedList: [], // 选中的商品
      baseUrl: 'http://121.89.213.194:3001/'
    }
  },
  // 函数
  methods: {
    // 获取数据
    async getData () {
      try {
        // 等待获取数据
        const res = await axios.get('http://121.89.213.194:3001/api/bottle')
        // 拿到数据存起来
        this.list = res.data.data
        // console.log(this.list)
      } catch (error) {
        console.log(error) // 打印错误
      }
    },
    // 添加一项
    add (item, index) {
      this.selectedList.push({ item, index })
    },
    remove (ind) {
      this.selectedList.splice(ind, 1)
    },
    removeItem (ind, index) {
      this.remove(ind)
      // console.log(this.$refs.products)
      this.$refs.products[index].removeItem()
    }
  },
  // 创建后
  created () {
    // 调用接口拿数据
    this.getData()
  }
}
</script>

<style lang="scss" scoped>
.home {
  width: 14.4rem;
  margin: 0 auto;
}

.list {
  display: flex;
  flex-wrap: wrap;
  overflow: hidden;
  overflow-y: auto;
  align-content: start;
  height: 100vh;
  padding-top: 0.4rem;

  &::-webkit-scrollbar {
    display: none;
  }
}
</style>
